package com.hxh.rpc.consumer;

import com.hxh.rpc.model.RpcRequest;
import com.hxh.rpc.model.RpcResponse;
import com.hxh.rpc.registry.ServiceRegistry;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.InvocationHandler;

import java.lang.reflect.Method;
import java.util.UUID;

/**
 * Rpc调用动态代理实现
 *
 * @author hxh
 * @date 2022/3/2
 * @since 1.0
 */
@Slf4j
@Data
public class RpcInvokeHandler<T> implements InvocationHandler {
    private String serviceVersion;

    private ServiceRegistry serviceRegistry;

    public RpcInvokeHandler(String serviceVersion, ServiceRegistry serviceRegistry) {
        this.serviceVersion = serviceVersion;
        this.serviceRegistry = serviceRegistry;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        RpcRequest rpcRequest = RpcRequest.builder()
                .bizNo(UUID.randomUUID().toString())
                .className(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .serviceVersion(this.serviceVersion)
                .paramTypes(method.getParameterTypes())
                .paramValues(args)
                .build();
        log.info("begin rpcRequest: {}", rpcRequest);
        RpcConsumerNettyHandler rpcConsumerNettyHandler = new RpcConsumerNettyHandler();
        RpcResponse rpcResponse = rpcConsumerNettyHandler.sendRpcRequest(rpcRequest);
        log.info("result rpcResponse: {}", rpcResponse);
        return rpcResponse.getData();
    }
}
